﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Elf.Common
{
    public static class ActivatorExtension
    {
        /// <summary>
        /// Creates a generic instance of the specified type using the constructor that best
        /// matches the specified parameters.
        /// </summary>
        /// <param name="generic">Type to create.</param>
        /// <param name="innerType">Generic type.</param>
        /// <param name="args">The arguments.</param>
        /// <returns></returns>
        public static T CreateGenericInstance<T>(Type generic, Type innerType, params object[] args)
        {
            if (generic == null) throw new ArgumentNullException("generic");
            if (innerType == null) throw new ArgumentNullException("innerType");
            if (args == null) throw new ArgumentNullException("args");

            Type specificType = generic.MakeGenericType(new System.Type[] { innerType });
            return (T)Activator.CreateInstance(specificType, args);
        }

        /// <summary>
        /// Creates a generic instance of the specified type using the constructor that best
        /// matches the specified parameters.
        /// </summary>
        /// <param name="generic">Type to create.</param>
        /// <param name="innerType">Generic type.</param>
        /// <param name="args">The arguments.</param>
        /// <returns></returns>
        public static object CreateGenericInstance(Type generic, Type innerType, params object[] args)
        {
            if (generic == null) throw new ArgumentNullException("generic");
            if (innerType == null) throw new ArgumentNullException("innerType");
            if (args == null) throw new ArgumentNullException("args");

            Type specificType = generic.MakeGenericType(new System.Type[] { innerType });
            return Activator.CreateInstance(specificType, args);
        }

    }
}
